package pl.lw.csvfilter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Vector;

public class CsvFilter {
    public static void main(String[] args) {
        try {
            File file = new File("./");
            File dir = new File("./filtered");
            dir.mkdir();
            String[] filenames = file.list();
            Vector<String> files = new Vector<String>();
            for (int i=0; i<filenames.length;i++) {
                if (filenames[i].endsWith(".csv")
                    || filenames[i].endsWith(".txt")) {
                    files.add(filenames[i]);
                }
            }
            System.out.print("Filtering ");
            for (int i=0; i<files.size();i++) {
                String name = files.get(i);
                System.out.print(".");
                FileReader filereader = new FileReader(name);
                FileWriter writer = new FileWriter("filtered/" + name);
                BufferedReader reader = new BufferedReader(filereader);
                String line = reader.readLine();
                while (line!=null) {
                    if (line!="") {
                        if (line.contains(",")) {
                            String[] ar = line.split(",");
                            String s = ar[ar.length-2] + "," + ar[ar.length-1] +
                                                                        "\r\n";
                            writer.write(s);
                        } else if (line.contains("\t")){
                            String[] ar = line.split("\t");
                            String s = ar[ar.length-2] + "," + ar[ar.length-1] +
                                                                        "\r\n";
                            writer.write(s);
                        } else {
                            System.out.println("Line: " + line);
                            System.out.println("has a wrong file format.");
                        }
                        line = reader.readLine();
                    }
                }
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("\nFiltering finished.");
        }
    }
}